package com.example.composableexample.animate

import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.SpringSpec
import androidx.compose.animation.core.spring
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay


@Preview
@Composable
fun BouncyLoader() {
    val yOffset = remember {
        Animatable(0f)
    }
    val scale = remember {
        Animatable(1f)
    }

    LaunchedEffect(key1 = "bouncyLoader") {
        delay(400)
        yOffset.animateTo(0.5f, bouncyAnimationSpec)
        scale.animateTo(50f, bouncyAnimationSpec)
        delay(500)
        scale.animateTo(10f, bouncyAnimationSpec)
        delay(500)
        scale.animateTo(50f, bouncyAnimationSpec)
    }
    val size = remember {
        mutableStateOf(IntSize.Zero)
    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .onSizeChanged { size.value = it }
    ) {
        GradientCircle(
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .size(26.dp)
                .graphicsLayer {
                    scaleX = scale.value
                    scaleY = scale.value
                    translationY = yOffset.value * size.value.height
                }
        )
        Text(
            text = "Compose", fontWeight = FontWeight.ExtraBold, modifier = Modifier.align(
                Alignment.Center
            )
        )
    }
}

@Composable
fun GradientCircle(modifier: Modifier = Modifier) {
    val brush = remember {
        Brush.verticalGradient(listOf(Color(0xFFC51162), Color(0xFFFFD600), Color(0xFFFF6D00)))
    }
    Canvas(modifier = modifier) {
        drawCircle(brush = brush)
    }
}

val bouncyAnimationSpec: SpringSpec<Float> = spring(
    dampingRatio = Spring.DampingRatioMediumBouncy,
    stiffness = Spring.StiffnessLow
)